<form
  lay-filter="purchaseSignForForm"
  id="purchaseSignForForm"
  class="layui-form open-form"
>
  <div class="open-model" id="purchaseSignForFormContent">
    <div class="open-auto">
      <input name="id" type="hidden" />
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label">入库类型</label>
          <div class="layui-input-block">
            <input
              id="inventoryTypeCode"
              name="inventoryTypeCode"
              type="hidden"
            />
            <input
              type="hidden"
              name="supplierId"
              disabled
              class="layui-input adv-disable"
              hidden
            />
            <select
              id="inventoryType"
              name="inventoryType"
              lay-filter="inventoryType"
            ></select>
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label">运单编号/报工单号</label>
          <div class="layui-input-block">
            <select
              id="signTaskId"
              name="signTaskId"
              lay-filter="signTaskId"
            ></select>
            <input id="signTaskNo" name="signTaskNo" type="hidden" />
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label">签收任务编号</label>
          <div class="layui-input-block">
            <input
              type="text"
              name="logisticsNo"
              disabled
              class="layui-input adv-disable"
            />
          </div>
        </div>
      </div>
      <!--            <div class="layui-col-xs3">-->
      <!--                <div class="layui-form-item">-->
      <!--                    <label class="layui-form-label">所属工单</label>-->
      <!--                    <div class="layui-input-block">-->
      <!--                        <input type="text" name="sn" disabled class="layui-input adv-disable"/>-->
      <!--                    </div>-->
      <!--                </div>-->
      <!--            </div>-->

      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label">创建人部门</label>
          <div class="layui-input-block">
            <input
              type="text"
              name="departmentName"
              disabled
              class="layui-input adv-disable"
            />
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label">创建人</label>
          <div class="layui-input-block">
            <input
              type="text"
              name="creatorName"
              disabled
              class="layui-input adv-disable"
            />
          </div>
        </div>
      </div>
      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label">创建时间</label>
          <div class="layui-input-block">
            <input
              type="text"
              name="createTime"
              disabled
              class="layui-input adv-disable"
            />
          </div>
        </div>
      </div>

      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label">供应商编码</label>
          <div class="layui-input-block">
            <input
              type="text"
              name="supplierCode"
              disabled
              class="layui-input adv-disable"
            />
          </div>
        </div>
      </div>

      <div class="layui-col-xs3">
        <div class="layui-form-item">
          <label class="layui-form-label">供应商名称</label>
          <div class="layui-input-block">
            <input
              type="text"
              name="supplierName"
              disabled
              class="layui-input adv-disable"
            />
          </div>
        </div>
      </div>

      <div id="logisticsContent"></div>

      <div class="layui-form-item">
        <button class="layui-btn" type="button" id="Configure">
          选择签收物料信息
        </button>
        <table
          class="layui-table"
          id="purchaseSignForFormTable"
          lay-filter="purchaseSignForFormTable"
        ></table>
      </div>
    </div>
    <div class="layui-form-item text-right">
      <button
        class="layui-btn layui-btn-primary"
        type="button"
        ew-event="closeDialog"
      >
        关闭
      </button>
      <button
        class="layui-btn"
        lay-filter="formSubmit"
        type="button"
        lay-submit
      >
        提交
      </button>
    </div>
  </div>
</form>
<script type="text/html" id="logisticsTemp">
  <div class="layui-col-xs12">
    <div class="purchaseSignForForm-title">
      <h3 class="title">物流信息</h3>
    </div>
    <div class="line" style="margin-bottom: 15px;"></div>
  </div>
  <div class="layui-col-xs3">
    <div class="layui-form-item">
      <label class="layui-form-label">物流记录编号</label>
      <div class="layui-input-block">
        <input
          type="text"
          name="logisticsNo"
          disabled
          class="layui-input adv-disable"
        />
      </div>
    </div>
  </div>
  <div class="layui-col-xs3">
    <div class="layui-form-item">
      <label class="layui-form-label">运输方式</label>
      <div class="layui-input-block">
        <input
          type="text"
          name="transportModeDesc"
          disabled
          class="layui-input adv-disable"
        />
      </div>
    </div>
  </div>
  <div class="layui-col-xs3">
    <div class="layui-form-item">
      <label class="layui-form-label">物流公司</label>
      <div class="layui-input-block">
        <input
          type="text"
          name="logisticsCompany"
          disabled
          class="layui-input adv-disable"
        />
      </div>
    </div>
  </div>
  <div class="layui-col-xs3" style="display: none" id="plateNoDiv">
    <div class="layui-form-item">
      <label class="layui-form-label">车牌号</label>
      <div class="layui-input-block">
        <input
          type="text"
          name="plateNo"
          disabled
          class="layui-input adv-disable"
        />
      </div>
    </div>
  </div>
  <div class="layui-col-xs3" style="display: none" id="courierNoDiv">
    <div class="layui-form-item">
      <label class="layui-form-label">快递单号</label>
      <div class="layui-input-block">
        <input
          type="text"
          name="courierNo"
          disabled
          class="layui-input adv-disable"
        />
      </div>
    </div>
  </div>
  <div class="layui-col-xs3">
    <div class="layui-form-item">
      <label class="layui-form-label">联系电话</label>
      <div class="layui-input-block">
        <input
          type="text"
          name="phone"
          disabled
          class="layui-input adv-disable"
        />
      </div>
    </div>
  </div>
  <div class="layui-col-xs3">
    <div class="layui-form-item">
      <label class="layui-form-label">物流录入类型</label>
      <div class="layui-input-block">
        <input
          type="text"
          name="enterTypeName"
          disabled
          class="layui-input adv-disable"
        />
      </div>
    </div>
  </div>
  <div class="layui-col-xs3">
    <div class="layui-form-item">
      <label class="layui-form-label">录入人</label>
      <div class="layui-input-block">
        <input
          type="text"
          name="deliveryCreatorName"
          disabled
          class="layui-input adv-disable"
        />
      </div>
    </div>
  </div>
  <div class="layui-col-xs3">
    <div class="layui-form-item">
      <label class="layui-form-label">物流录入时间</label>
      <div class="layui-input-block">
        <input
          type="text"
          name="deliveryCreateTime"
          disabled
          class="layui-input adv-disable"
        />
      </div>
    </div>
  </div>
</script>
<script type="text/html" id="purchaseSignForFormTableBar">
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script>
  layui.use(
    ["layer", "form", "table", "admin", "laydate", "upload", "laytpl"],
    async function () {
      var $ = layui.jquery;
      var layer = layui.layer;
      var form = layui.form;
      var table = layui.table;
      var config = layui.config;
      var admin = layui.admin;
      var upload = layui.upload;
      let laydate = layui.laydate;
      let laytpl = layui.laytpl;
      const nowData = { ...parentData };
      const data = nowData.data;
      //入库类型
      // var inventoryType=nowData.data?nowData.data.code:'';
      let deliveryRecordProductList = [];
      //入库类型列表
      $("#Configure").hide();
      if (nowData.eventName == "detail") {
        admin.setFormDisable("#purchaseSignForFormContent", true);
      }

      await admin.initDataSelectPro(
        "enterprisecab/warehouse/admin/warehouseInventoryType/list",
        {
          inventoryType: "in",
          limit: 9999,
          status: "enable",
          ids: nowData.operateTypes ? 12 : "",
        },
        "inventoryType",
        "入库类型",
        async function (selectData, obj) {
          // inventoryType = obj.code;
          console.log("生产类型", obj);
          $("#logisticsContent").html("");
          table.reload("purchaseSignForFormTable", {
            data: [],
          });
          $("#Configure").hide();
          $("#signTaskId").empty();
          form.val("purchaseSignForForm", {
            signTaskId: "",
            creatorName: "",
            createTime: "",
            logisticsNo: "",
          });
          form.render("select");
          //出入库类型编码-赋值
          if (selectData.value) {
            $("#inventoryTypeCode").val(obj.code);
            if (obj.code == "CGR") {
              $("#Configure").show();
              laytpl(logisticsTemp.innerHTML).render({}, function (html) {
                $("#logisticsContent").html(html);
              });
              await admin.initDataSelectPro(
                "enterprise/purchase/admin/purchaseDeliveryRecord/list",
                {
                  limit: 99999,
                  filterWarehousingComplete: 1,
                },
                "signTaskId",
                "运单编号",
                (d, obj) => {
                  if (d.value) {
                    $("#signTaskNo").val(obj.code);
                    obj.deliveryCreatorName = obj.creatorName;
                    obj.deliveryCreateTime = obj.createTime;
                    form.val("purchaseSignForForm", obj);
                    if (obj.transportMode == 0) {
                      $("#plateNoDiv").show();
                      $("#courierNoDiv").hide();
                    } else {
                      $("#plateNoDiv").hide();
                      $("#courierNoDiv").show();
                    }
                  }
                },
                "waybillNo"
              );
            } else if (obj.code == "SCR") {
              await admin.initDataSelectPro(
                "production/productionPlan/admin/productionTheWorkOrder/list",
                { limit: 99999, type: 2 },
                "signTaskId",
                "报工单号",
                (d, obj) => {
                  $("#signTaskNo").val(obj.code);
                  obj.logisticsNo = obj.workOrderCode;
                  form.val("purchaseSignForForm", obj);
                  obj.quantity = obj.workQuantity;
                  obj.hasSignQuantity = obj.signedNum;
                  if (!obj.signNum && obj.quantity != null) {
                    obj.signNum = obj.quantity;
                  }
                  table.reload("purchaseSignForFormTable", {
                    data: [obj],
                  });
                },
                "code"
              );
            } else if (obj.code == "THR-02") {
              // 销售退货入库
              admin.req(
                "enterprise/sell/admin/customerReturnType/list",
                { limit: 9999, status: 3 },
                (res) => {
                  console.log(123, res);
                }
              );
            }
          } else {
            $("#inventoryTypeCode").val("");
            $("#signTaskNo").val("");
          }
        }
      );

      if (nowData.operateTypes == "qianShou") {
        // 设置默认值并渲染
        form.val("purchaseSignForForm", {
          inventoryType: "12", // 设置默认选中值
        });

        $("#inventoryTypeCode").val("CGR");
        $("#Configure").show();
        laytpl(logisticsTemp.innerHTML).render({}, function (html) {
          $("#logisticsContent").html(html);
        });
        await admin.initDataSelectPro(
          "enterprise/purchase/admin/purchaseDeliveryRecord/list",
          {
            limit: 99999,
            /*    filterWarehousingComplete: 1,*/
            id: data.id,
          },
          "signTaskId",
          "运单编号",
          (d, obj) => {
            if (d.value) {
              console.log("1", obj);
            }
          },
          "waybillNo"
        );

        form.val("purchaseSignForForm", {
          signTaskId: data.id, // 设置默认选中值
          signTaskNo: data.waybillNo, // 设置默认选中值
          deliveryCreatorName: data.deliveryCreatorName,
          deliveryCreateTime: data.createTime,
        });
        form.val("purchaseSignForForm", data);
        if (data.transportMode == 0) {
          $("#plateNoDiv").show();
          $("#courierNoDiv").hide();
        } else {
          $("#plateNoDiv").hide();
          $("#courierNoDiv").show();
        }
        form.render("select");

        admin.req(
          "enterprise/purchase/admin/purchaseDeliveryRecordProduct/list",
          { limit: 99999, page: 1, purchaseDeliveryRecordId: data.id },
          function (res) {
            layer.closeAll("loading");
            if (res.code == 200) {
              let dataS = res.data;
              for (let i = 0; i < dataS.length; i++) {
                /*           dataS[i].purchaseOrderDetailId =  dataS[i].id;*/
                deliveryRecordProductList.push(dataS[i]);
              }
              // 获取数据集合并传入表格中
              table.reload("purchaseSignForFormTable", {
                data: deliveryRecordProductList,
                limit: deliveryRecordProductList.length,
              });
            } else {
              layer.msg(res.msg, { icon: 2 });
            }
          },
          "GET"
        );
      }

      table.render({
        elem: "#purchaseSignForFormTable",
        data: [],
        page: false,
        cellMinWidth: 100,
        cols: [
          [
            { type: "numbers", align: "center", height: 70, title: "序号" },
            {
              field: "purchaseSignForId",
              align: "center",
              title: "签收ID",
              hide: "true",
            },
            { field: "signProductId", title: "签收产品ID", hide: "true" },
            {
              field: "productTypeId",
              align: "center",
              title: "物料类型",
              hide: "true",
            },
            {
              field: "productPic",
              align: "center",
              title: "物料图片",
              hide: "true",
              width: 140,
              templet: function (d) {
                return '<img src="' + d.productPic + '" id="platformPic"/>';
              },
            },
            {
              field: "skuCode",
              align: "center",
              title: "物料编号",
              width: 120,
            },
            {
              field: "skuName",
              align: "center",
              title: "物料名称",
              width: 120,
            },

            /*  {
          field: 'subUnitCode',
          align: 'center',
          title: '计量单位code',
          width: 60,
        },  {
            field: 'subUnitId',
            align: 'center',
            title: '计量单位id',
            width: 60,
          },
          {
            field: 'mainUnitName',
            align: 'center',
            title: '计量单位名称',
            width: 60,
          },*/

            { field: "skuSpec", align: "center", title: "规格号", width: 120 },
            { field: "baseUnitName", align: "center", title: "基础单位" },
            {
              field: "purchaseQuantity",
              align: "center",
              title: "采购数量",
              templet: function (d) {
                let purchaseQuantity = d.purchaseQuantity;
                let mainUnitName = d.mainUnitName;
                if (purchaseQuantity || purchaseQuantity == 0) {
                  if (mainUnitName) {
                    return d.purchaseQuantity + "" + d.mainUnitName;
                  }
                  return d.purchaseQuantity;
                } else {
                  return "";
                }
              },
            },
            {
              field: "quantity",
              align: "center",
              title: "发货数量",
              templet: function (d) {
                return d.quantity + "" + d.mainUnitName;
              },
            },
            {
              field: "hasSignQuantity",
              align: "center",
              title: "已签收数",
              templet: function (d) {
                let hasSignQuantity = d.hasSignQuantity;
                let mainUnitName = d.mainUnitName;
                if (hasSignQuantity || hasSignQuantity == 0) {
                  if (mainUnitName) {
                    return d.hasSignQuantity + "" + d.mainUnitName;
                  }
                  return d.hasSignQuantity;
                } else {
                  return "";
                }
              },
            },
            {
              field: "surplusSignQuantity",
              align: "center",
              title: "待签收数",
              templet: function (d) {
                let hasSignQuantity = d.hasSignQuantity;
                let quantity = d.quantity || 0;
                let mainUnitName = d.mainUnitName;
                if (hasSignQuantity || hasSignQuantity == 0) {
                  if (mainUnitName) {
                    return quantity - d.hasSignQuantity + "" + d.mainUnitName;
                  }
                  return quantity - d.hasSignQuantity;
                } else {
                  return "";
                }
              },
            },
            {
              field: "signNum",
              align: "center",
              title: "签收数(主计量)",
              width: 170,
              /* templet: admin.setTableInput('signNum', nowData.eventName == 'detail', 'signNum'),*/
              templet: function (d) {
                // ⭐⭐⭐ 关键一步：如果 signNum 没有值，则赋值为 quantity
                // if (!d.signNum && d.quantity != null) {
                //   d.signNum = d.quantity;
                // }
                // 然后再调用封装的方法渲染 input 输入框
                return admin.setTableInput(
                  "signNum",
                  nowData.eventName == "detail",
                  "signNum"
                )(d);
              },
            },
            // , {field: 'mainUnitRate', align: 'center', title: '主计量单位换算率',}
            {
              field: "subUnitNum",
              align: "center",
              title: "辅计量单位数",
              width: 120,
            },
            {
              field: "subUnitName",
              align: "center",
              title: "辅计量单位名称",
              hide: "true",
            },
            {
              field: "subUnitRate",
              align: "center",
              title: "辅计量单位换算率",
              hide: "true",
            },
            {
              field: "baseUnitNum",
              align: "center",
              title: "基础单位数",
              width: 120,
              templet: admin.setTableInput("baseUnitNum", true),
            },
            {
              align: "center",
              toolbar: "#purchaseSignForFormTableBar",
              hide: nowData.eventName == "detail",
              title: "操作",
              width: 100,
              fixed: "right",
            },
          ],
        ],
        done: function () {
          // 监听输入框-签收数量
          admin.tableInputChangeByClass(
            "purchaseSignForFormTable",
            "signNum",
            function (index, value, tableData) {
              var baseUnitName = tableData[index].baseUnitName;
              var mainUnitRate = tableData[index].mainUnitRate;
              var subUnitName = tableData[index].subUnitName;
              var subUnitRate = tableData[index].subUnitRate;
              if (mainUnitRate !== null && mainUnitRate !== "") {
                var baseUnitNum = (value * mainUnitRate).toFixed(2);
                tableData[index].baseUnitNum = baseUnitNum;
                $(`[data-index=${index}]`)
                  .find(`[data-field=baseUnitNum]`)
                  .find("div")
                  .text(baseUnitNum + "" + baseUnitName); // 更新显示
                //数据回显
                // $(this).closest("tr").find("td").each(function () {
                //     if ($(this).data("field") == "baseUnitNum") {
                //         $(this).find("div").text(baseUnitNum + "" + baseUnitName);
                //     }
                // });
                //辅计量数据
                if (subUnitRate !== null && subUnitRate !== "") {
                  var subUnitNum = baseUnitNum / subUnitRate;
                  var roundSubUnitNum = Number(subUnitNum.toFixed(4));
                  tableData[index].subUnitNum = subUnitNum;
                  $(`[data-index=${index}]`)
                    .find(`[data-field=subUnitNum]`)
                    .find("div")
                    .text(roundSubUnitNum + "" + subUnitName); // 更新显示

                  // deliveryRecordProductList[curIndex].subUnitNum = roundSubUnitNum;
                  //数据回显
                  // $(this).closest("tr").find("td").each(function () {
                  //     if ($(this).data("field") == "subUnitNum") {
                  //         $(this).find("div").text(roundSubUnitNum + "" + subUnitName);
                  //     }
                  // });
                }
              }
              // 计算
            }
          );
        },
      });
      if (data && data.id) {
        let code = data.code;
        if (code == "SCR") {
          await admin.initDataSelectPro(
            "production/productionPlan/admin/productionTheWorkOrder/list",
            { limit: 99999 },
            "signTaskId",
            "报工单号",
            (d, obj) => {
              obj.logisticsNo = obj.workOrderCode;
              form.val("purchaseSignForForm", obj);
              obj.quantity = obj.workQuantity;
              obj.hasSignQuantity = obj.signedNum;
              table.reload("purchaseSignForFormTable", {
                data: [obj],
              });
            },
            "code"
          );
        } else if (code == "CGR") {
          if (nowData.eventName != "detail") {
            $("#Configure").show();
          }
          laytpl(logisticsTemp.innerHTML).render({}, function (html) {
            $("#logisticsContent").html(html);
          });
          await admin.initDataSelectPro(
            "enterprise/purchase/admin/purchaseDeliveryRecord/list",
            {
              limit: 99999,
              filterWarehousingComplete: 1,
            },
            "signTaskId",
            "运单编号",
            (d, obj) => {
              if (d.value) {
                obj.deliveryCreatorName = obj.creatorName;
                obj.deliveryCreateTime = obj.createTime;
                form.val("purchaseSignForForm", obj);
                if (obj.transportMode == 0) {
                  $("#plateNoDiv").show();
                  $("#courierNoDiv").hide();
                } else {
                  $("#plateNoDiv").hide();
                  $("#courierNoDiv").show();
                }
              }
            },
            "waybillNo"
          );
        }
        form.val("purchaseSignForForm", data);
        table.reload("purchaseSignForFormTable", {
          data: data.purchaseSignForProducts,
        });
      }

      $("#Configure").click(function () {
        if ($("#signTaskId").val()) {
          admin.formOpen({
            area: "90%",
            offset: "50px",
            title: "配置订单物料信息",
            path: "components/purchase/purchaseSignForFormTable.html",
            success: function () {
              console.log("inventoryTypeCode", $("#inventoryTypeCode").val());
              parentData.cacheList = [
                ...table.cache["purchaseSignForFormTable"],
              ];
              parentData.inventoryTypeCode = $("#inventoryTypeCode").val();
              parentData.id = $("#signTaskId").val();
            },
            end: function () {
              if (childData.list) {
                const newData = childData.list || [];
                const oldData = table.cache["purchaseSignForFormTable"];
                const list = newData.map((v) => {
                  const obj = oldData.find((v1) => v1.id === v.id);
                  if (obj) {
                    return { ...obj };
                  }
                  return v;
                });
                table.reload("purchaseSignForFormTable", {
                  data: list, // 设置新的数据
                });
              }
            },
          });
        } else {
          layer.msg("请先选择运单编号/报工单号", { icon: 2 });
        }
      });
      form.on("submit(formSubmit)", function (d) {
        const formData = { ...d.field };
        // formData.purchaseSignForProducts = table.cache['purchaseSignForFormTable'].map(v => {
        //     return {
        //         id: '',
        //         signNum: v.signNum,
        //         signProductId: v.id
        //     }
        // })

        formData.purchaseSignForProducts = table.cache[
          "purchaseSignForFormTable"
        ].map((v) => {
          return {
            id: nowData.eventName == "edit" ? v.id : "",
            signNum: v.signNum,
            signProductId: v.id,
            subUnitCode: v.subUnitCode,
            subUnitName: v.subUnitName,
            subUnitId: v.subUnitId,
          };
        });
        console.log(123, formData);

        // return;

        admin.req(
          "enterprise/purchase/admin/purchaseSignFor/add",
          JSON.stringify(formData),
          function (res) {
            layer.closeAll("loading");
            if (res.code == 200) {
              layer.msg(res.msg, { icon: 1 });
              table.reload("purchaseSignForTable");
              layer.closeAll("page");
            } else {
              layer.msg(res.msg, { icon: 2 });
            }
          },
          "POST",
          false,
          "application/json"
        );
        // if (nowData.eventName == 'add') {
        //     admin.req('enterprise/purchase/admin/purchaseSignFor/add', JSON.stringify(formData), function (res) {
        //         layer.closeAll('loading');
        //         if (res.code == 200) {
        //             layer.msg(res.msg, {icon: 1});
        //             table.reload('purchaseSignForTable');
        //             layer.closeAll('page');
        //         } else {
        //             layer.msg(res.msg, {icon: 2});
        //         }
        //     }, 'POST', false, "application/json");
        // }
      });
      table.on("tool(purchaseSignForFormTable)", function (obj) {
        var d = obj.data; // 获取当前行的数据
        var layEvent = obj.event; // 获取事件名（edit 或 del）
        if (obj.tr) {
          obj.tr.on("click", function (e) {
            e.preventDefault(); // 防止默认行为
          });
        }
        if (layEvent == "del") {
          const index = $(obj.tr[0]).data("index");
          let list = table.cache["purchaseSignForFormTable"].filter((v) => {
            return v["LAY_TABLE_INDEX"] != index;
          });
          table.reload("purchaseSignForFormTable", {
            data: list,
          });
        }
      });
    } 
  );
</script>

<style>
  #purchaseSignForForm .layui-form-label {
    width: 120px;
  }

  #purchaseSignForForm .layui-input-block {
    margin-left: 150px;
  }

  #purchaseSignForForm .layui-form-item .layui-inline {
    /* margin-bottom: 5px; */
    margin-right: 0px;
  }
</style>
